package com.example.jwtdemo.controller;

import com.example.jwtdemo.basecontroller.BaserController;
import com.example.jwtdemo.exception.entity.Result;
import com.example.jwtdemo.exception.entity.ResultCode;
import com.example.jwtdemo.pojo.Role;
import com.example.jwtdemo.pojo.User;
import com.example.jwtdemo.service.UserService;
import com.example.jwtdemo.utils.JwtUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys")
public class UserController extends BaserController {
    @Resource
    private UserService userService;
    @Resource
    private JwtUtils jwtUtils;

    @RequestMapping("/login")
    public Result login(String userName,String passWord){
        String jwt = "";
        User user = userService.findUserByUsername(userName);
        if (null != user){
            List<Role> roles = userService.findRoleByUsername(user.getUsername());
            StringBuilder sb = new StringBuilder();
            for (Role role : roles) {
                sb.append(role.getName());
            }
            Map<String,Object> map = new HashMap<>();
            map.put("roles",sb);
            map.put("userName",user.getUsername());
            jwt = jwtUtils.createJwt(String.valueOf(user.getId()), user.getUsername(), map);
            return new Result(ResultCode.SUCCESS,jwt);
        }else{
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
        }

    }
    @RequestMapping("/profile")
    public String profile(){
        System.out.println(userName);
        return userName;
    }
}
